package niu.fencer.tool.qrcode.util;

import android.util.Base64;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.zip.GZIPOutputStream;


public class Decoder {
	public byte[][] dataArray;
	public int curIndex=0;
	public boolean receiveAll=false;
	public int total=2;
	public int size=0;
	public ArrayList<Integer> ids=new ArrayList<Integer>();
	public String NO_NAME="NO_NAME";
	public String fileName=NO_NAME;
	public void receive(String strResult) {

		if(receiveAll) {
			return;
		}
		if(strResult!=null) {
			decode(strResult);
		}
	}
	public void decode(String strResult){
		if(receiveAll||strResult==null){
			return;
		}
		try{
			byte[] decodedStr=Base64.decode(strResult, Base64.DEFAULT);
			ByteBuffer byteBuffer = ByteBuffer.wrap(decodedStr);
			int  total=byteBuffer.getInt();
			int  index=byteBuffer.getInt();
			if(total<1||total<=index){
				receiveAll=true;
				return ;
			}

			if(dataArray==null) {
				dataArray=new byte[total][];
				this.total=total;
			}
			if(dataArray[index]==null) {
				byte[] splitData=new byte[decodedStr.length-8];
				byteBuffer.get(splitData);
				dataArray[index]=splitData;
				this.curIndex=index;
			}
			this.curIndex=index;
			if(!this.ids.contains(index)){
				this.ids.add(index);
			}
			int size=this.ids.size();
			this.size=size;
			if(this.total==size){
				receiveAll=true;
				this.fileName=new String(dataArray[0]);
			}
		}catch (Exception e){
			receiveAll=true;//解析错误 当做非文件二维码
			LogUtil.e("decode",e);
		}
	}

	public  byte[] toByteArray() {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		try {
			for (int i = 1; i < dataArray.length; i++) {
				out.write(dataArray[i]);
			}
		} catch (Exception e) {
			Log.e("gzip compress error.", e.getMessage());
		}
		return out.toByteArray();
	}
}
